package com.elong.android.specialhouse.utils;

import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dp.android.elong.crash.LogWriter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class JSONHelper {

	public final static String TAG = "JSONHelper";
	public final static int COMPRESS_THRESHHOLD = 5 * 1024;
	private final static byte[] DOWNLOAD_BUFFER = new byte[1024];


	public final static String validateJsonString(String str) {
		char c;
		StringBuffer buf = new StringBuffer(str);
		for (int i = 0, j = str.length(); i < j; i++) {
			c = str.charAt(i);
			if (c < ' ') {
				buf.setCharAt(i, ' ');
			}
		}
		return buf.toString();
	}

	private static JSONObject s_objNetworError;
	private static JSONObject s_objServerError;
	private static JSONObject s_objJsonError;
	public final static int EVENT_NETWORK_ERROR = 0;
	public final static int EVENT_SERVER_ERROR = 1;
	public final static int EVENT_JSON_ERROR = 2;
	public final static String KEY_JSONHELPER_ERROR = "jsonHelperError";
	public final static String KEY_JSONHELPER_ERRORCODE = "jsonHelperErrorCode";
	
	public final static String DEFAULT_KEY = "default_key";
	public final static ArrayList<HashMap<String, Object>> convertArray2List(JSONArray data,
			ArrayList<String> keysFilter) {
		if (data == null) {
			return null;
		}
		ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
		try {
			int len = data.size();
			for (int i = 0; i < len; i++) {
				Object o = data.get(i);
				if (o instanceof JSONObject) {
					result.add(convert2HashMap((JSONObject) o, keysFilter));
				} else {
					HashMap<String, Object> item = new HashMap<String, Object>();
					item.put(DEFAULT_KEY, o);
					result.add(item);
				}
			}
		} catch (Exception e) {
			LogWriter.logException(TAG, "", e);
		}
		return result;
	}
	
	public final static HashMap<String, Object> convert2HashMap(JSONObject obj, ArrayList<String> keysFilter) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			if (keysFilter != null) {
				int len2 = keysFilter.size();
				for (int j = 0; j < len2; j++) {
					String key = keysFilter.get(j);
					Object o = obj.get(key);
					if (o != null) {
						if (o instanceof JSONArray) {
							o = JSONHelper.convertArray2List((JSONArray) o, null);
						}
						result.put(key, o);
					}
				}
			} else {
				Iterator<String> iter = obj.keySet().iterator();
				while (iter.hasNext()) {
					String key = iter.next();
					Object o = obj.get(key);
					if (obj != null) {
						if (o instanceof JSONArray) {
							o = JSONHelper.convertArray2List((JSONArray) o, null);
						}
						result.put(key, o);
					}
				}
			}
		} catch (Exception e) {
			Log.e(TAG, "convert to hashtable failed!", e);
		}
		return result;
	}

}
